<%--
  Created by IntelliJ IDEA.
  User: 给
  Date: 2020/12/2
  Time: 18:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<jsp:useBean id="user" class="com.media.bean.UserBean"></jsp:useBean>
<jsp:setProperty name="user" property="*"></jsp:setProperty>

<%
    //加载数据库驱动
    Class.forName("com.mysql.jdbc.Driver");

    //建立数据库连接
    String url = "jdbc:mysql://localhost:3306/book"; //数据库连接地址
    Connection connection = DriverManager.getConnection(url,"root","root"); //第一个root为数据库的用户名  第二个root为数据库的密码

    //关闭自动提交功能
    connection.setAutoCommit(false);

    String sql = "insert into user (username,password,gender,age,id) values (?,?,?,?,?)"; //在PreparedStatement 中使用问好代替实际参数
    PreparedStatement ps = connection.prepareStatement(sql);

    ps.setString(1,user.getUsername());
    ps.setString(2,user.getPassword());
    ps.setInt(3,user.getGender());
    ps.setInt(4,user.getAge());
    ps.setInt(5,0);
    ps.addBatch();



    int[] count={0};
    try{
        //事务
        count = ps.executeBatch();
        connection.commit();
    }catch (SQLException e){
        connection.rollback();
        e.printStackTrace();
    }

    if(count[0] > 0){
        out.print("添加当前人员成功");
    }else{
        out.print("添加当前人员失败");
    }

    //response.setHeader("refresh","3;url=home.jsp");
%>